<template>
  <div>
    <el-card class="w_100" v-loading="spinning">
      <template #header>
        <header>
          <div class="left">区域合格证开具数量排名</div>
          <div class="right">
            <el-button @click='handleExportXlsMy' type="primary" size="small">下载</el-button>
            <el-select v-model="queryParam.selectUnitId" clearable size="mini" style="width: 120px;margin-left:10px;"
                       @change='unitIdClick' placeholder="请选择区域"
                       v-hasPermi="['nongjt:user:list']" >
              <el-option v-for="{id,area} of unitList" :key="id" :label="area" :value="id">
              </el-option>
            </el-select>
            <el-select v-model="queryParam.selectYear" size="mini" style="width: 80px;margin-left: 10px;"
                       @change='yearSelect'
                       placeholder="请选择年份">
              <el-option v-for="temp of yearList" :key="temp" :label="temp" :value="temp">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="queryParam.selectYearMonth" value-format="yyyy-MM" style="width: 110px;margin-left: 10px;"
              type="month" size="mini" placeholder="请选择月份">
            </el-date-picker>
          </div>
        </header>
      </template>

      <!--            绘图-->
      <div id='AreaSortCertificateCharts' style='height: 300px;width: 100%;'></div>
    </el-card>
  </div>
</template>

<script>
import {getAction, getActionSimple} from "@/utils/axiosUtils";
import {mapGetters} from "vuex";
import {echartResizeMixins} from "@/views/certificate/charts/echartResizeMixins";

let echarts = require('echarts')

export default {
  name: 'AreaSortCertificateCharts',
  mixins:[echartResizeMixins],
  data() {
    return {
      description:'区域合格证开具数量排名',
      title:'区域合格证开具数量排名',
      url:{
        AreaSortCertificate:'/certificate/certificate_count/AreaSortCertificate',
        exportXlsUrl: '/certificate/certificate_count/exportXlsAreaSort'
      },
      spinning:false,
      //查询参数
      queryParam: {
        //默认年份
        selectYear: new Date().getFullYear(),
        //默认年月
        selectYearMonth: null,
        //选中的单位id
        selectUnitId: null
      },
      //图表相关
      chart: null,
      option: {
        title: {
          text: '',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel : {//坐标轴刻度标签的相关设置。
            formatter : function(params){
              let newParamsName = "";// 最终拼接成的字符串
              let paramsNameNumber = params.length;// 实际标签的个数
              let provideNumber = 4;// 每行能显示的字的个数
              let rowNumber = Math.ceil(paramsNameNumber / provideNumber);// 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                for (let p = 0; p < rowNumber; p++) {
                  let tempStr = "";// 表示每一次截取的字符串
                  let start = p * provideNumber;// 开始截取的位置
                  let end = start + provideNumber;// 结束截取的位置
                  // 此处特殊处理最后一行的索引值
                  if (p === rowNumber - 1) {
                    // 最后一次不换行
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    // 每一次拼接字符串并换行
                    tempStr = params.substring(start, end) + "\n";
                  }
                  newParamsName += tempStr;// 最终拼成的字符串
                }

              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
              }
              //将最终的字符串返回
              return newParamsName
            }
          }
          //
          // axisLabel: {
          //   interval: 0,
          //   // rotate: 45,
          // }
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'item',
          formatter: ' {b} 开具数量:{c}'
        },
        //保存为图片，等其他功能,在右上角
        toolbox: {
          feature: {
            saveAsImage: { show: true }
          }
        },
        series: [{
          data: [],
          type: 'bar',
          showBackground: true,
          label: {
            show: true,
            formatter: '{c}',
            position: 'top',
            color: '#5470c6',
            fontSize: 12
          },
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          },
          itemStyle: {
            color: function (params) {
              //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
              let colorList = ['#73c0de','#ee6666','#91cc75','#c23531',
                '#fc8452', '#61a0a8', '#d48265', '#91c7ae',
                '#749f83', '#5470c6'];
              if (params.dataIndex >= colorList.length) {  //给大于颜色数量的柱体添加循环颜色的判断

                return colorList[params.dataIndex % colorList.length]
              }
              return colorList[params.dataIndex]
            }
          }
        }]
      },
      //总量
      total:0,
    }
  },
  created(){
    this.queryParam.selectUnitId = this.selectUnitId
    setTimeout(() => {
      this.getStatistics({ yearStr: this.queryParam.selectYear + '-01-01' ,unitId:this.queryParam.selectUnitId})
    }, 500);

  },
  computed:{
    ...mapGetters([
      'unitList',
      'selectUnitId',
      'yearList'
    ]),
  },
  methods:{
    initChart() {
      if (!this.chart) {
        const dom = document.querySelector('#AreaSortCertificateCharts')
        this.chart = echarts.init(dom)
        this.chart.on('click',(params)=>{
          const {name} = params

          let selectTime = this. queryParam.selectYear
          let dateBegin = selectTime + '-01-01'
          let dateEnd = selectTime + '-12-31'
          this.$router.push({ path: 'certificate/certificate?companyName=' + name + '&dateBegin=' + dateBegin + '&dateEnd=' + dateEnd});
        })
      }
      this.chart.setOption(this.option)
    },
    //获取数据
    async getStatistics(param) {
      try {
        try {
          this.spinning = true
          const result = await getActionSimple(this.url.AreaSortCertificate, param)
          // console.log(result)
          //设置x轴
          this.option.xAxis.data = result.map(t=>t.title)
          //设置y轴
          this.option.series[0].data = result.map(t=>t.count)
          //展示统计数量
          this.total = this.option.series[0].data.reduce((pre,cur)=>pre+cur,0)
          // this.option.title.text = this.area + this.title +"("+this.total+")"
          this.option.title.text = this.title +"("+this.total+")"
          // console.log(this.option.series[0].data)
          //设置子标题 展示查询的日期
          this.setChartsSubtext(param)

          this.initChart()
        } catch (e) {
          console.log(e)
        }
      } catch (e) {
        console.log(e)
      } finally {
        this.spinning = false
      }
    },
    //年份选择事件
    yearSelect(year) {
      let param = {
        yearStr: year,
        unitId:this.queryParam.selectUnitId
      }
      this.getStatistics(param)
      //清空月份
      this.queryParam.selectYearMonth = null
    },
    //区域选择事件
    unitIdClick(n) {
      if (n) {
        let param = {
          unitId: n,
          yearMonthStr : this.queryParam.selectYearMonth
        }
        if (this.queryParam.selectYear) {
          param.yearStr = this.queryParam.selectYear + '-01-01'
        }
        this.getStatistics(param)
        //设置图标
        const { area } = this.unitList.find(t => t.id === n)
        this.area = area
        // this.setCharts(area)
      }
    },
    //设置图表子标题
    setChartsSubtext(param) {
      //设置子标题 展示查询的日期
      let { yearStr, yearMonthStr } = param
      if (yearMonthStr) {
        this.option.title.subtext = yearMonthStr.substring(0, 7)
      } else if (yearStr) {
        this.option.title.subtext = yearStr.substring(0, 4)
      } else {
        this.option.title.subtext = new Date().getFullYear()
      }
    },
    //导出
    async handleExportXlsMy() {
      this.spinning = true
      try {
        let param = {
          unitId : this.queryParam.selectUnitId,
          yearStr : this.queryParam.selectYear,
          yearMonthStr: this.queryParam.selectYearMonth
        }
        console.log("导出参数",param)

        this.download(this.url.exportXlsUrl, {
          ...param
        }, `区域合格证开具数量排名.xlsx`)
      }finally {
        this.spinning = false
      }
    },
  },
  watch: {
    //监听可查询的年限列表
    yearList(n) {
      if (n.length > 0) {
        const year = n[0]
        //更新双向绑定的年份
        this.queryParam.selectYear = year
      }
    },
    selectUnitId(n){
      this.queryParam.selectUnitId = n
    },
    //监听年月的选择
    'queryParam.selectYearMonth'(n){
      if (n) {
        //更新一下前面的年份
        this.queryParam.selectYear = n.split("-")[0]
        let param = {
          yearMonthStr:n,
          unitId : this.queryParam.selectUnitId
        }
        this.getStatistics(param)
      } else {
        //如果清空,默认查询最新年份
        this.queryParam.selectYear = this.yearList[0]
        const param = {
          yearStr: this.queryParam.selectYear,
          unitId : this.queryParam.selectUnitId
        }
        this.getStatistics(param)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.w_100{
  width: 100%;
}
header{
  display: flex;
  justify-content: space-between;
  align-content: center;

  .left{
    font-weight: bold;
  }
}
</style>
